﻿using Frameworks;
using UnityEngine;
using UnityEngine.SceneManagement;
using DotNetClient;

#if UNITY_EDITOR
using System.IO;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
#endif

public class PreloadScene : MonoBehaviour
{
    public string firstLoadSceneName = "FirstScene";    // 方便进入游戏时跳转到指定的游戏场景
    public string loadingSceneName = "Loading";         // 加载场景的进度显示的场景名称
    public GUI_ID firstModule;

    private void Awake()
    {
        DontDestroyOnLoad(this);
        Initialize();
    }

    private void Initialize()
    {
        //Screen.fullScreen = true;
        //Screen.SetResolution(1920, 1080, true);
        //QualitySettings.SetQualityLevel(4);
        //QualitySettings.antiAliasing = 4;
        //Application.targetFrameRate = 60;
        //RenderSettings.ambientLight = Color.white;
        //Input.multiTouchEnabled = false;
        //GameGlobal.TIME_START_GAME = System.DateTime.Now.Ticks;
        //Application.runInBackground = true;
        //Screen.sleepTimeout = SleepTimeout.NeverSleep;
        
        //Debugger.EnableDebugLogs(true);
        Debugger.EnableOnScreen(true);
        //Debugger.EnableOnText(true);

        GameManager.Instance.Initialize(this, firstLoadSceneName);
        GameManager.SceneMgr.SetupLoadingScene(loadingSceneName);
    }

    private void Start()
    {
        GameManager.Instance.Start();

        UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnFirstSceneLoaded;
        GameManager.SceneMgr.LoadSceneByLoading(firstLoadSceneName);
    }

    private void OnFirstSceneLoaded(Scene sceneName, LoadSceneMode mode)
    {
        if (sceneName.name != firstLoadSceneName) return;

        UnityEngine.SceneManagement.SceneManager.sceneLoaded -= OnFirstSceneLoaded;
        if (firstModule != GUI_ID.None) GameManager.GUIMgr.Display(firstModule);
    }

    private void Update()
    {
#if UNITY_EDITOR
        if (Input.GetKeyDown(KeyCode.P))
        {
            Debugger.Log("Pause program!");
            UnityEditor.EditorApplication.isPaused = true;
        }
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            //Debugger.Log("Stop program!");
            UnityEditor.EditorApplication.isPlaying = false;
        }
#else
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Debugger.Log("Exit program!");
            System.Diagnostics.Process.GetCurrentProcess().Kill();
            System.Environment.Exit(0);
            Application.Quit();
        }
#endif
        NetworkManager.Instance.Update();
        GameManager.Instance.Update();
    }

    private void FixedUpdate()
    {
        GameManager.Instance.FixedUpdate();
    }

    private void OnApplicationPause(bool isPause)
    {
        GameManager.Instance.OnApplicationPause(isPause);
    }

    private void OnApplicationQuit()
    {
        NetworkManager.Instance.Dispose();
        GameManager.Instance.OnApplicationQuit();
    }

    private void OnDestroy()
    {
        Debugger.Log("Close program!");
        GameManager.Instance.Dispose();
    }

    [RuntimeInitializeOnLoadMethod]
    private static void StartupScene()
    {
        if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name != "Preload")
        {
            UnityEngine.SceneManagement.SceneManager.LoadScene("Preload");
        }
    }
}

#if UNITY_EDITOR
[CustomEditor(typeof(PreloadScene))]
public class PreloadSceneEditor : Editor
{
    private PreloadScene _component;
    private List<string> _sceneNames;
    private List<int> _sceneIndexes;
    private int _popupIndex;

    public void OnEnable()
    {
        _component = (PreloadScene)target;
        _sceneNames = new List<string>();
        _sceneIndexes = new List<int>();

        EditorBuildSettingsScene[] existingScenes = EditorBuildSettings.scenes;
        for (int i = 0, j = 0; i < existingScenes.Length; i++)
        {
            EditorBuildSettingsScene scene = existingScenes[i];
            if (scene.enabled)
            {
                string name = Path.GetFileNameWithoutExtension(scene.path);
                if (name != "Preload" && name != "Loading")
                {
                    _sceneNames.Add(name);
                    _sceneIndexes.Add(j++);
                }
            }
        }

        for (int i = 0; i < _sceneNames.Count; i++)
        {
            if (_component.firstLoadSceneName == _sceneNames[i])
            {
                _popupIndex = i;
                break;
            }
        }
    }

    public override void OnInspectorGUI()
    {
        bool changed = false;

        string oldSceneName = _component.firstLoadSceneName;
        _popupIndex = EditorGUILayout.IntPopup("FirstLoadSceneName", _popupIndex, _sceneNames.ToArray(), _sceneIndexes.ToArray());
        _component.firstLoadSceneName = _sceneNames[_popupIndex];
        if (oldSceneName != _component.firstLoadSceneName) changed = true;

        if (changed)
        {
            //EditorUtility.SetDirty(_component);
            //EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetSceneByName("Preload"));
            EditorSceneManager.SaveScene(EditorSceneManager.GetSceneByName("Preload"));
        }
    }
}
#endif